﻿@model ProductModel

@using Telerik.Web.Mvc.UI;

<div>
    <h4 class="mb-4">@T("Admin.Catalog.Products.ProductVariantAttributes.Attributes")</h4>

    @if (Model.Id > 0)
	{
		if (Model.NumberOfAvailableProductAttributes > 0)
		{
			<script>
				function onProductVariantAttributeEdit(e) {
					if (e.mode == "edit") {
						$('#AttributeControlType')
							.data('select-selected-id', e.dataItem['AttributeControlTypeId'])
							.data('select-init-text', e.dataItem['AttributeControlType'])
							.val(e.dataItem['AttributeControlTypeId'])
							.trigger('change');

						$('#ProductAttribute')
							.data('select-selected-id', e.dataItem['ProductAttributeId'])
							.data('select-init-text', e.dataItem['ProductAttribute'])
							.val(e.dataItem['ProductAttributeId'])
							.trigger('change');
					}

					var id = parseInt(e.dataItem['Id']);

					if (id === 0) {
						$(e.form).find('#IsRequired').prop('checked', true);
					}
					else {
						var optionsSetsChoice = $('#OptionsSetsContainer' + id);

						if (optionsSetsChoice.find('option').length > 0) {
							$('#EditOptionsLink' + id).hide();
							optionsSetsChoice.show();
							$('#OptionsSetsChoice' + id).selectWrapper();
						}
					}
				}

				function onProductVariantAttributeRowDataBound(e) {
					var id = parseInt(e.dataItem['Id']);

					$('#EditOptionsLink' + id).show();
					$('#OptionsSetsContainer' + id).hide();
				}
			</script>

			@(Html.Telerik().Grid<ProductModel.ProductVariantAttributeModel>()
				.Name("productvariantattributes-grid")
				.DataKeys(keys =>
				{
					keys.Add(x => x.Id);
				})
				.DataBinding(dataBinding =>
				{
					dataBinding.Ajax()
						.Select("ProductVariantAttributeList", "Product", new { productId = Model.Id })
						.Insert("ProductVariantAttributeInsert", "Product", new { productId = Model.Id })
						.Update("ProductVariantAttributeUpdate", "Product")
						.Delete("ProductVariantAttributeDelete", "Product");
				})
				.Columns(columns =>
				{
					columns.Bound(x => x.ProductAttribute)
						.Width("16%");
					columns.Bound(x => x.AttributeControlType)
						.Width("16%");
					columns.Bound(x => x.TextPrompt)
						.Width("16%");
					columns.Bound(x => x.IsRequired)
						.Width("10%")
						.ClientTemplate(@Html.SymbolForBool("IsRequired"))
						.Centered();
					columns.Bound(x => x.DisplayOrder1)
						.Width("10%")
						.Centered();
					columns.Bound(x => x.ViewEditUrl)
						.Width("16%")
						.ClientTemplate(
							"<a id='EditOptionsLink<#= Id #>' href='<#= ViewEditUrl #>' class='text-truncate'><#= ViewEditText #></a>" +
							"<div id='OptionsSetsContainer<#= Id #>' style='display:none'><select class='form-control' id='OptionsSetsChoice<#= Id #>' data-valcount='<#= ValueCount #>'><#= OptionsSets #></select></div>"
						)
						.ReadOnly()
						.Title(T("Admin.Catalog.Products.ProductVariantAttributes.Attributes.Values").Text);
					columns.Command(commands =>
					{
						commands.Edit().Localize(T);
						commands.Delete().Localize(T);
					})
					.Width("20%")
					.HtmlAttributes(new { align = "right" });
				})
				.ToolBar(commands => commands.Insert() )
				.ClientEvents(events =>
				{
					events.OnEdit("onProductVariantAttributeEdit");
					events.OnRowDataBound("onProductVariantAttributeRowDataBound");
				})
				.EnableCustomBinding(true))
        }
        else
        {
            <div class="alert alert-danger">
                @T("Admin.Catalog.Products.ProductVariantAttributes.NoAttributesAvailable")
            </div>
        }
    }
    else
    {
        <div class="alert alert-danger">
            @T("Admin.Catalog.Products.ProductVariantAttributes.SaveBeforeEdit")
        </div>
    }
</div>

<div class="mt-5">
    <h4 class="mb-4">@T("Admin.Catalog.Products.ProductVariantAttributes.AttributeCombinations")</h4>

    @if (Model.Id > 0)
    {
        if (Model.NumberOfAvailableProductAttributes > 0)
        {
            <div class="alert alert-info">
                @T("Admin.Catalog.Products.ProductVariantAttributes.AttributeCombinations.Description")
            </div>

            <div class="mb-3">

                <input type="submit" id="btnRefreshCombinations" name="btnRefreshCombinations" class="d-none" />
                <script>
                    $(document).ready(function () {
                        $('.add-new-combination').on('click', function (e) {
                        	openPopup('@(Url.Action("AttributeCombinationCreatePopup", "Product", new { productId = Model.Id }))&btnId=btnRefreshCombinations&formId=product-form');
                            return false;
                        });

                        $('#btnRefreshCombinations').click(function () {
                            //refresh grid
                            var optionsGrid = $("#attributecombinations-grid");
                            optionsGrid.data('tGrid').ajaxRequest();

                            //return false to don't reload a page
                            return false;
                        });

                        $('#btnCreateAllCombinations, #btnDeleteAllCombinations').click(function () {
                            $(this).doAjax({
                                callbackSuccess: function (resp) {
                                    $('#btnRefreshCombinations').click();
                                }
                            });
                        });
                    });
                </script>
            </div>
            <div>
				<script>
					function onRowDataBound_Combinations(e) {
						if (!e.dataItem.IsActive) {
							$(e.row).find('td').wrapInner('<span class="text-muted" />');
						}
					}
				</script>
				
				@(Html.Telerik().Grid<ProductVariantAttributeCombinationModel>()
					.Name("attributecombinations-grid")
					.DataKeys(keys =>
					{
						keys.Add(x => x.Id);
					})
					.Columns(columns =>
					{
						columns.Bound(x => x.AttributesXml)
							.ClientTemplate("<a href=\"#\" onclick=\"" + "openPopup('" + @Url.Content("~/Admin/Product/AttributeCombinationEditPopup/") + "<#= Id #>?btnId=btnRefreshCombinations&formId=product-form'); return false;\"><#= AttributesXml #></a><br /><span style=\"color: red\"><#= Warnings #></span>")
							.Width(460)
							.Encoded(false)
							.ReadOnly();
						columns.Bound(x => x.IsActive)
							.Width(80)
							.Template(item => @Html.SymbolForBool(item.IsActive))
							.ClientTemplate(@Html.SymbolForBool("IsActive"))
							.Centered();
						columns.Bound(x => x.ProductUrl)
							.Width(120)
							.Centered()
							.ClientTemplate("<a href=\"<#= ProductUrl #>\" target=\"_blank\"><#= ProductUrlTitle #></a>");
						columns.Bound(x => x.Sku);
						columns.Bound(x => x.Price)
							.Format("{0:0.00}")
							.RightAlign();
						columns.Bound(x => x.StockQuantity)
							.Width(160)
							.Centered();
						columns.Bound(x => x.AllowOutOfStockOrders)
							.Width(60)
							.HeaderTemplate("<span class='t-link'><i class=\"fa fa-sort-numeric-up\" title=\"" + @T("admin.catalog.products.productvariantattributes.attributecombinations.fields.allowoutofstockorders").Text + "\"></i></span>")
							.Template(item => @Html.SymbolForBool(item.AllowOutOfStockOrders))
							.ClientTemplate(@Html.SymbolForBool("AllowOutOfStockOrders"))
							.Centered();
						//columns.Bound(x => x.Id)
						//    .Width(90)
						//    .Centered()
						//    .ClientTemplate("<button onclick=\"" + "openPopup('" + @Url.Content("~/Admin/Product/AttributeCombinationEditPopup/") + "<#= Id #>?btnId=btnRefreshCombinations&formId=product-form'); return false;\" class='btn'>" + @T("Admin.Common.Edit").Text + "</button>")
						//    .Title("");
						columns.Command(commands =>
						{
							commands.Delete().Localize(T);
						})
						.HtmlAttributes(new { align = "right" })
						.Width(90);
					})
					.Pageable(settings => settings.PageSize(100).Position(GridPagerPosition.Both))
					.DataBinding(dataBinding =>
					{
						dataBinding.Ajax()
							.Select("ProductVariantAttributeCombinationList", "Product", new { productId = Model.Id })
							.Delete("ProductVariantAttributeCombinationDelete", "Product");
					})
					.ClientEvents(events => events.OnRowDataBound("onRowDataBound_Combinations"))
					.ToolBar(commands => commands.Template(AttributeCombinationsGridCommands))
					.EnableCustomBinding(true))
            </div>
        }
        else
        {
            <div class="alert alert-danger">
                @T("Admin.Catalog.Products.ProductVariantAttributes.NoAttributesAvailable")
            </div>
        }
    }
    else
    {
        <div class="alert alert-danger">
            @T("Admin.Catalog.Products.ProductVariantAttributes.SaveBeforeEdit")
        </div>
    }
</div>

@helper AttributeCombinationsGridCommands(Grid<ProductVariantAttributeCombinationModel> grid)
{
	<button class="t-button t-grid-add add-new-combination">
		@T("Admin.Catalog.Products.ProductVariantAttributes.AttributeCombinations.AddNew")
	</button>

	<button type="button" id="btnCreateAllCombinations" class="t-button ml-auto" data-url='@Url.Action("CreateAllAttributeCombinations", new { productId = Model.Id })'
			data-ask="@T("Admin.Catalog.Products.ProductVariantAttributes.AttributeCombinations.AskToCombineAll")">
		<i class="fa fa-tasks"></i>
		<span>@T("Admin.Catalog.Products.ProductVariantAttributes.AttributeCombinations.CreateAllCombinations")</span>
	</button>

	<button type="button" id="btnDeleteAllCombinations" class="t-button t-grid-cancel-changes" data-url='@Url.Action("DeleteAllAttributeCombinations", new { productId = Model.Id })'
			data-ask="@T("Admin.Catalog.Products.ProductVariantAttributes.AttributeCombinations.AskToDeleteAll")">
		<i class="far fa-trash-alt"></i>
		<span>@T("Admin.Catalog.Products.ProductVariantAttributes.AttributeCombinations.DeleteAllCombinations")</span>
	</button>
}